package com.xinyue.ext.reader.bean;

import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import com.xinyue.ext.exception.BeanException;
import com.xinyue.ext.reader.ParamHolder;
import com.xinyue.ext.util.StringUtil;

public class OrderReader extends BeanContext{
	//私有构造器
	private OrderReader() {
	}
	//私有内部类
	private static class SingletonHolder{
        private static OrderReader instance = new OrderReader();  
    }
	/**
	 * 获得实例对象
	 * @param holder 
	 */
	public static OrderReader getInstance(ParamHolder holder) {
		BeanContext.holder = holder;
		return SingletonHolder.instance;
	}

	/**
	 * 读取order-by标签数据
	 * param e entity
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void read(Element e) throws BeanException {
		Element order = e.element(order_by_);
		
		if(order != null) {
			List<Element> os = order.elements(order_column_);
			if(os == null || os.size() == 0) {
				throw new BeanException("order-by标签必须定义order-column子标签", holder.getException());
			}else {
				String orderBy = " order by ";
				
				for (Element o: os) {
					String by = o.attributeValue(by_);
					String name = o.attributeValue(name_);
					//验证name属性是否合法
					if(StringUtil.isNull(name)) {
						throw new BeanException("order-column标签name属性未定义或其值为空", holder.getException());
					}
					
					Node n = e.selectSingleNode("id[@name='" + name + "']");
					if(n == null) {
						n = e.selectSingleNode("property[@name='" + name + "']");
					}
					if(n == null) {
						throw new BeanException("order-column标签name属性值非法:" + name, holder.getException());
					}
					
					//验证order并合成Hql语句
					if(StringUtil.isNull(by)) {
						by = "ASC";
					}else if(!"DESC".equals(by) && !"ASC".equals(by)){
						throw new BeanException("order-column标签by属性值非法:" + by, holder.getException());
					}
					
					orderBy += name + " " + by + ", ";
				}
				
				orderBy = orderBy.substring(0, orderBy.length() - 2);
				
				holder.getEntity().setOrder(orderBy);
			}
		}
	}
}
